package com.xuwei.chatroom.controller;


import com.xuwei.chatroom.entity.User;
import com.xuwei.chatroom.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author xuwei
 * @since 2020-08-06
 */
@Controller
@Slf4j
public class UserController {
    @Resource
    private IUserService userService;

    @Resource
    private ServletContext servletContext;

    /**
     * 登录页跳转
     */
    @GetMapping({"/toLogin", "/login"})
    public String toLogin() {
        return "/login";
    }

    /**
     * 用户登录
     *
     * @param user 用户
     * @return 处理信息
     */
    @PostMapping("/login")
    public ResponseEntity<String> login(@RequestBody User user, HttpServletRequest request) {
        if (user == null) {
            return ResponseEntity.badRequest().body("用户不能为空");
        }
        if (Strings.isBlank(user.getUsername()) || Strings.isBlank(user.getPassword())) {
            return ResponseEntity.badRequest().body("用户名或密码不能为空");
        }
        log.info("用户:{}校验登录", user);

        //根据用户名获取用户
        User byUsername = userService.findByUsername(user.getUsername());

        if (byUsername == null) {
            return ResponseEntity.badRequest().body("用户不存在");
        }
        if (!byUsername.getPassword().equals(user.getPassword())) {
            return ResponseEntity.badRequest().body("用户名或密码错误");
        }

        log.info("用户:{}登录", byUsername.getUsername());
        //将上一次登录的session清空，防止出现一个用户多个session
//        request.getSession().invalidate();
        Map<User, HttpSession> userMap = (HashMap<User, HttpSession>) servletContext.getAttribute("userMap");
        //判断用户是否存在Map集合中，存在则销毁原来的
        if (userMap.containsKey(byUsername)) {
            //返回true，说明用户存在
            HttpSession session = userMap.get(byUsername);
            //存在则销毁该用户
            session.invalidate();
        }
        request.getSession().setAttribute("USER", byUsername);

        log.info("用户Session:{}登录", request.getSession().getAttribute("USER"));

        //获取全局的消息列表
        AtomicReference<String> sourceMessage = new AtomicReference<>("");
        if (null != servletContext.getAttribute("message")) {
            sourceMessage.set(servletContext.getAttribute("message").toString());
        }
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(sourceMessage.get())
                .append("系统公告：<font color='gray'>")
                .append(byUsername.getUsername())
                .append("走进了聊天室！</font><br>");
        //设置消息
        servletContext.setAttribute("message", stringBuffer.toString());

        return ResponseEntity.ok("登录成功");
    }

    /**
     * 注册页跳转
     */
    @GetMapping({"/toRegister", "/register"})
    public String toRegister() {
        return "/register";
    }

    /**
     * 用户注册
     *
     * @param user 用户
     * @return 处理信息
     */
    @PostMapping("/register")
    public ResponseEntity<String> register(@RequestBody User user) {
        if (user == null) {
            return ResponseEntity.badRequest().body("用户不能为空");
        }
        if (Strings.isBlank(user.getUsername()) || Strings.isBlank(user.getPassword())) {
            return ResponseEntity.badRequest().body("用户名或密码不能为空");
        }
        log.info("用户：{}校验注册", user.getUsername());

        //保存用户
        boolean save = userService.save(user);
        if (!save) {
            return ResponseEntity.badRequest().body("用户注册失败，请稍后再试");
        }
        log.info("用户注册成功:{}", user.getUsername());
        return ResponseEntity.ok("注册成功");
    }

    /**
     * 跳转到用户信息页面
     */
    @GetMapping("/userInfo")
    public String userInfo(HttpServletRequest request, Model model) {
        User user = (User) request.getSession().getAttribute("USER");
        User byId = userService.getById(user.getId());
        model.addAttribute("user", byId);
        return "/user_info";
    }

    /**
     * 修改用户信息
     * @param user 用户
     * @return 修改结果
     */
    @PostMapping("/user")
    public ResponseEntity<String> editUserInfo(@RequestBody User user, HttpServletRequest request, Model model) {
        if (user == null) {
            return ResponseEntity.badRequest().body("用户不能为空");
        }
        if (Strings.isBlank(user.getUsername())) {
            return ResponseEntity.badRequest().body("用户名不能为空");
        }
        log.info("用户：{}编辑信息校验", user.getUsername());
        boolean update = userService.updateById(user);
        if (!update) {
            return ResponseEntity.badRequest().body("用户名信息修改失败，请稍后再试");
        }
        //获取修改后的用户
        User newUser = userService.getById(user.getId());

        log.info("用户信息修改成功:{}", newUser.getUsername());

        //清除原来的session
        request.getSession().invalidate();

        model.addAttribute("user", newUser);

        Map<User, HttpSession> userMap = (Map<User, HttpSession>) servletContext.getAttribute("userMap");
        // 判断用户是否已经在map集合中'
        if (userMap.containsKey(user)) {
            // 说用map中有这个用户.
            HttpSession session = userMap.get(user);
            // 将这个session销毁.
            session.invalidate();
        }
        request.getSession().setAttribute("USER", newUser);

        return ResponseEntity.ok("修改成功");
    }

    /**
     * 退出登录
     */
    @GetMapping("/user/logout")
    public String logout(HttpServletRequest request) {
        // 获得session对象
        HttpSession session = request.getSession();
        // 销毁session
        session.invalidate();
        return "redirect:/login";
    }
}

